package com.lidy.tankbattle.event;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * @author lidy
 * @version V1.0
 * @classname BallMove
 * @description 小球通过键盘控制移动，体现Java的事件控制
 * @date 2022/5/28 16:14
 */
public class BallMove extends JFrame{
    MyPanel mp;
    int width = 1000;
    int height = 750;
    public static void main(String[] args) {
        new BallMove();
    }

    public BallMove() {
        mp = new MyPanel(width, height);
        this.add(mp);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(width, height);
        this.setVisible(true);
        // 窗口JFrame可以监听键盘事件，即可以监听到面板发生的键盘事件
        this.addKeyListener(mp);
    }
}
/**
 * @author: lidy
 * @description: KeyListener是键盘监听器
 * @date: 2022/5/28 16:24
 */

class MyPanel extends JPanel implements KeyListener {
    /**
     * 为了小球可以移动，把小球左上角的x，y设置成变量
    **/

    private final int PANEL_WIDTH;

    private final int PANEL_HEIGHT;
    private int x = 10;
    private int y = 10;

    public MyPanel(int panelWidth, int panelHeight) {
        this.PANEL_WIDTH = panelWidth;
        this.PANEL_HEIGHT = panelHeight;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.black);
        g.fillOval(x, y, 20, 20);
    }
    /**
     * 有字符输出时，该方法会触发
    **/
    @Override
    public void keyTyped(KeyEvent e) {

    }

    /**
     * 当某个键按下时，该方法会触发
     **/
    @Override
    public void keyPressed(KeyEvent e) {
        // 根据按下的不同键，来处理小球的移动（上下左右移动）
        // 向下的箭头
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            if (y < PANEL_HEIGHT) {
                y++;
            }
        } else if (e.getKeyCode() == KeyEvent.VK_UP) {
            if (y > 0) {
                y--;
            }
        } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            if (x > 0) {
                x--;
            }
        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            if (x < PANEL_WIDTH) {
                x++;
            }
        }
        // 让面板重画小球
        this.repaint();
    }

    /**
     * 当某个键放开时，该方法会触发
     **/
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
